package com.spring.library.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spring.library.common.Result;
import com.spring.library.entity.User;
import com.spring.library.mapper.UserMapper;
import com.spring.library.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spring.library.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author danty
 * @since 2024-09-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result register(User user) {
        //1. 校验用户名和邮箱是否存在
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();// 这玩意是一个查询条件封装类
        wrapper.eq(User::getUserName, user.getUserName());// 这里的eq方法其实是sql语句中的where条件判断
        LambdaQueryWrapper<User> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(User::getUserEmail, user.getUserEmail());

        // selectOne就相当于一个select的sql语句，条件是wrapper，查询第一条数据
        if (userMapper.selectOne(wrapper) != null) {
            return Result.error("用户名已存在");
        }
        if (userMapper.selectOne(wrapper1) != null) {
            return Result.error("邮箱冲突");
        }

        //2. MD5 加密
        String md5String = Md5Util.getMD5String(user.getUserPassword());
        user.setUserPassword(md5String);

        user.setUserRole("USER");
        user.setUserStatus("0"); // 默认状态 0正常 1禁用

        // 插入数据
        userMapper.insert(user);
        return Result.success();
    }

    @Override
    public User findByName(String username) {
        return userMapper.findByUserName(username);
    }


}
